package org.yoao.moneymachine.business.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.yoao.crm.struts.form.FileForm;
import org.yoao.moneymachine.bean.File;
import org.yoao.moneymachine.business.service.IFileService;
import org.yoao.moneymachine.dao.FileDAO;

/**
 * @author  Weishion.Yi
 * @description
 * @date 2010-10-6 下午01:39:10
 */
public class FileServiceImpl implements IFileService {
	private static final Logger log = Logger.getLogger(FileServiceImpl.class);
	private FileDAO fileDAO = new FileDAO();

	@Override
	public String add(FileForm form) throws Exception {
		File file = new File();
		BeanUtils.copyProperties(file, form);
		if(fileDAO.insert(file) > -1)
			return "[SUCCESS]";
		else
			return "[FAILURE]";
	}

	@Override
	public void delete(String rootPath, String id) throws Exception {
		String[] idArray = id.split(",");
		if(idArray != null && idArray.length > 0){
			for(int i=0;i<idArray.length;i++){
				String sid = idArray[i];
				File resourceFile = fileDAO.findById(sid);
				String path = resourceFile.getFileUrl();
				int index = path.indexOf("/resource/");
				if(index > -1) path = path.substring(index, path.length());
				java.io.File file = new java.io.File(rootPath + path);
				if(file.exists()){
					if(file.delete()){
						fileDAO.delete(sid);
					}
				}else{
					log.info("删除资源文件:"+file.getAbsolutePath()+"不存在!");
					System.out.println("删除资源文件:"+file.getAbsolutePath()+"不存在!");
				}
			}
		}
	}

	@Override
	public int getDataCount(Map map) throws Exception {
		return fileDAO.getDataCount(map);
	}

	@Override
	public List view(int startRow, int endRow, Map map) throws Exception {
		return fileDAO.find(startRow, endRow, map);
	}
}
